package com.max.back.demo.api;

import cn.hutool.core.bean.BeanUtil;
import com.max.back.common.http.ResponseResult;
import com.max.back.demo.entity.Dept;
import com.max.back.demo.form.CountDeleteForm;
import com.max.back.demo.form.DeptForm;
import com.max.back.demo.service.DeptSer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * DeptCtl
 */
@CrossOrigin
@RestController
@RequestMapping("/api/dept")
public class DeptCtl {
    @Autowired
    private DeptSer ser;
    @PostMapping("/add")
    public ResponseResult<Boolean> add(@RequestBody @Validated({DeptForm.Base.class}) DeptForm form) {
        Dept dept = BeanUtil.toBean(form, Dept.class);
        boolean res = ser.save(dept);
        if (res) {
            return ResponseResult.getSuccessResult(true, "A006", null);
        } else {
            return ResponseResult.getMessageResult(false, "A007");
        }
    }
    @PostMapping("/delete")
    public ResponseResult<Boolean> delete(@RequestBody @Validated({DeptForm.Delete.class}) DeptForm form) {
        boolean res = ser.removeById(form.getId());
        if (res) {
            return ResponseResult.getSuccessResult(true, "A006", null);
        } else {
            return ResponseResult.getMessageResult(false, "A007");
        }
    }
    @PostMapping("/countdelete")
    public ResponseResult<Boolean> countdelete(@RequestBody @Valid CountDeleteForm form) {
        boolean res = false;
        for (Integer id : form.getIds()) {
            res = ser.removeById(id);
        }
        if (res) {
            return ResponseResult.getSuccessResult(true, "A006", null);
        } else {
            return ResponseResult.getMessageResult(false, "A007");
        }
    }
    @PostMapping("/update")
    public ResponseResult<Boolean> update(@RequestBody @Validated({DeptForm.Update.class}) DeptForm form) {
        Dept dept = BeanUtil.toBean(form, Dept.class);
        boolean res = ser.updateById(dept);
        if (res) {
            return ResponseResult.getSuccessResult(true, "A006", null);
        } else {
            return ResponseResult.getMessageResult(false, "A007");
        }
    }
    @PostMapping("/find")
    public ResponseResult<List<Dept>> find(@RequestBody @Validated({DeptForm.Find.class}) DeptForm form) {
        List<Dept> deptList = ser.finddept(form.getNum(), form.getClas(), form.getType());
        return ResponseResult.getSuccessResult(deptList);
    }
}
